<?php ob_start();if(!isset($_SESSION)){
  session_start();$message="";
} require_once('../../../Connections/microassur.php'); require_once('../../utils/fonctions.php');?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}





$col_rs_tarif=1;
$requete1=mysql_query("select * from contrat,garantiesouscrite where contrat.Numero_contrat='".$_SESSION['num_contrat']."' and contrat.Identifiant_contrat=garantiesouscrite.Identifiant_contrat ") or die(mysql_error());
if($requete1 && mysql_num_rows($requete1))
{
$reponse1=mysql_fetch_array($requete1);
$col_rs_tarif=$reponse1['Identifiant_formule']; 
}
//if(isset($_POST['MM_insert']))$vide=!empty($_POST['datereglement']) && !empty($_POST['refreglement']) && !empty($_POST['montantecheanceregle'])   ;
//if(isset($_POST['MM_insert']))$bool=datevalide($_POST['datereglement']) && datevalider($_POST['datereglement']) && verifLibelle('refreglement') && verifNumeric($_POST['montantecheanceregle'])  && ( !empty($_POST['montantassure']) && verifNumeric($_POST['montantassure']))  &&  (!empty($_POST['montantdroitentre']) && verifNumeric($_POST['montantdroitentre'])) ;

mysql_select_db($database_microassur, $microassur);
$query_rs_tarif = sprintf("SELECT * FROM tarif WHERE Identifiant_formule = %s", GetSQLValueString($col_rs_tarif, "int"));
$rs_tarif = mysql_query($query_rs_tarif, $microassur) or die(mysql_error());
$row_rs_tarif = mysql_fetch_assoc($rs_tarif);
$totalRows_rs_tarif = mysql_num_rows($rs_tarif); 
if( $totalRows_rs_tarif>0 && isset($_POST['MM_insert']) && $_POST['MM_insert']=='form1'  )
{
//echo "*********************".$_SESSION['formule'];
	//$_SESSION['tarif']=$row_rs_tarif['Montant_tarif_base'];
	
	
	//$bool=
	//if(1)
		$req=mysql_query("select * from contrat where Numero_contrat='".$_SESSION['num_contrat']."'");
		$rep=mysql_fetch_array($req);
		$freqpaiment=$rep['Frequence_paiement'];
		if($freqpaiment=='A')$_SESSION['tarif']= 0;
		if($freqpaiment=='M')$_SESSION['tarif']= $row_rs_tarif['Taux_echeance_mensuel'];
		if($freqpaiment=='T')$_SESSION['tarif']=$row_rs_tarif['Taux_echeance_trimestriel'];
		if($freqpaiment=='S')$_SESSION['tarif']=$row_rs_tarif['Taux_echeance_semestriel'];
		
	if($row_rs_tarif['Type_tarif']=='M')
	{	//2.1
		$montantcotisation=ceil($row_rs_tarif['Montant_tarif_base']+ ($row_rs_tarif['Montant_tarif_base']* $_SESSION['tarif']));
	}
	elseif($row_rs_tarif['Type_tarif']=='T' && !empty($_POST['montantassure']))
	{
				//2.2
				$montant_int=$row_rs_tarif['Taux_tarif_base'] * $_POST['montantassure']; 
				$montantcotisation=ceil($montant_int + ($montant_int * $_SESSION['tarif']));
	}
	//if($_POST['montantcotis']!=$montantcotisation)$message.="<br>Inégalité montant cotisation";
	if($row_rs_tarif['Type_tarif']=='T' && !empty($_POST['montantassure']))
	{
		//3
		$montant_int=$row_rs_tarif['Taux_tarif_base'] * $_POST['montantassure']; 
		$montantfraisecheance=ceil($montant_int * $_SESSION['tarif']);
		//if($_POST['fraisecheance']!=$montantfraisecheance)$message.="<br>Inégalité montant frais echeance";
	}
	elseif($row_rs_tarif['Type_tarif']=='M')
	{ 
		
		$montantfraisecheance=ceil($row_rs_tarif['Montant_tarif_base']* $_SESSION['tarif']);	
		//if($_POST['fraisecheance']!=$montantfraisecheance)$message.="<br>Inégalité montant frais echeance";
	}
$_SESSION['montantcotisation']=$montantcotisation;
	$_SESSION['montantfraisecheance']=$montantfraisecheance;
	if( isset($_POST['MM_insert']) && $_POST['MM_insert']=='form1')
	{
		//4
	/*	if($_POST['freqpaiement']=='A')$nbreglement=1;
		if($_POST['freqpaiement']=='M')$nbreglement=12;
		if($_POST['freqpaiement']=='T')$nbreglement=4;
		if($_POST['freqpaiement']=='S')$nbreglement=2;
		
		$montantecheance=$montantcotisation/$nbreglement;*/
		if(1)//$message.="<br>Inégalité montant  echeance";
		//else
		{
		//echo "*********************";		
			//5
			$m1=1 ;
			$m=1;
			$date=1 ;
			$message1="";
			$n=1;
			$bool =true;//verifDate($_SESSION['dateeffet'],$_POST['datereglement']); 
			if(!$bool){	$date=0;}
			
					//echo $_SESSION['dateeffet'];
					
				//6
				/*if(!empty($_POST['montantassure']) && $row_rs_tarif['Type_tarif']=='M'){$m=0;}
				
				
				//7
					
					if(empty($_POST['montantassure']) && $row_rs_tarif['Type_tarif']=='T'){$m1=0;}
					if($_POST['montantecheanceregle']!=$montantecheance){$n=0; }*/

					if($m1==1 && $m==1 && $date==1 && $n==1)
					{ 
						//echo "*********************";		
						//8
						//$montantassure= $_POST['montantassure'];
						 mysql_query("START TRANSACTION"); $verif=true;
						$req=mysql_query("update contrat set Mode_paiement='".$_POST['modepaiement']."'  where Numero_contrat='".$_SESSION['num_contrat']."'")or die(mysql_error());
						
						if(!$req) { mysql_query("rollback");$verif=false; $message.=colorer("Problème modification contrat (informations paiement), contactez la DSI ","false");} 
						else mysql_query("commit");
						/*	$_SESSION['modepaiement']=$_POST['modepaiement'];
						
						//9
						$datefincotis=ajoutDate($_SESSION['dateeffet'],12,-1,0);
						//$requete=mysql_query("select * from cotisation where Date_debut_cotisation='".."' and Date_fin_cotisation='".."' and Numero_avenant_cotisation='".."' and Montant_base_cotisation='".."' and ");
						// Vérifier si une insertion
						 mysql_query("START TRANSACTION");
						$req1=mysql_query("insert into cotisation values('','".dateEN2FR($_SESSION['dateeffet'])."','".dateEN2FR($datefincotis)."','".$_POST['refreglement']."','".$row_rs_tarif['Montant_tarif_base']."','".$montantfraisecheance."','".$_POST['montantdroitentre']."','".$_SESSION['idcontrat']."')") or die(mysql_error());
						if(!$req1) {  mysql_query("rollback");$verif=false; $message.=colorer("Problème création cotisation, contactez la DSI","false");}
						else  mysql_query("commit");
						
						//Création des variables de session pour alimenter le formlaire
							$_SESSION['modepaiement']=$_POST['modepaiement'];
							$_SESSION['fredpaiement']=$_POST['freqpaiement'];
							$_SESSION['montantcotis']=$_POST['montantcotis'];
							
							$_SESSION['refreglement']=$_POST['refreglement'];
							$_SESSION['fraisecheance']=$_POST['fraisecheance'];
							$_SESSION['datereglement']=$_POST['datereglement'];
							$_SESSION['refreglement']=$_POST['refreglement'];
							$_SESSION['montantecheanceregle']=$_POST['montantecheanceregle'];
							$_SESSION['montantdroitentre']=$_POST['montantdroitentre'];
							$_SESSION['montantassure']=$_POST['montantassure'];
							$_SESSION['montantcotisation']=$montantcotisation;
							$_SESSION['montantecheance']=$montantecheance;
							$_SESSION['montantfraisecheance']=$montantfraisecheance;
											
						
						$max=-1;
						$requete=mysql_query("select max(Identifiant_cotisation) as id from cotisation ")or die(mysql_error());
						if($requete)
						{
							 $reponse=mysql_fetch_array($requete);
							 $max=$reponse["id"]; 
						 }
						else $verif=false;
						//10
						
						//calcul du premier échéance 	
						$i=0;
						if($nbreglement==12) $nbmois =1;
						
						if($nbreglement==2)$nbmois =6;
;
						if($nbreglement==4)$nbmois =3;

						if($nbreglement==1)$nbmois =12;
						
						
						
					 	$datefin=ajoutDate($_SESSION['dateeffet'],$nbmois,-1,0);
						
						 
						$req=mysql_query("select * from echeancier where Date_debut_echeance='".dateEN2FR($_SESSION['dateeffet'])."' and Date_fin_echeance='".dateEN2FR($datefin)."' and Etat_echeance='R' and Montant_echeance='$montantecheance' and Identifiant_cotisation='".$max."'"); 
						
						$num=0;
						if($req)
						{
							
							$num=mysql_num_rows($req);
						}
						else $verif=false;
						//echo $datefin;
						 if($num==0)
						 {
						 $req=mysql_query("insert into echeancier values('','".dateEN2FR($_SESSION['dateeffet'])."','".dateEN2FR($datefin)."','R','$montantecheance','".$max."')"); 
						 if(!$req)$message.=colorer("Problème création échéance, contactez la DSI ","false");
						 }
						
						$datedebut=ajoutDate($datefin,0,1,0);
						$i++;
						while($i<$nbreglement)
						{ 
						
							if($nbreglement==12) $nbmois =1;
							
							if($nbreglement==2)$nbmois =6;
	;
							if($nbreglement==4)$nbmois =3;
	
							if($nbreglement==1)$nbmois =12;
							
							//$datedebut=ajoutDate($datedebut,$nbmois,1,0);
							$datefin=ajoutDate($datedebut,$nbmois,-1,0);
							 
							$req=mysql_query("select * from echeancier where Date_debut_echeance='".dateEN2FR($datedebut)."' and Date_fin_echeance='".dateEN2FR($datefin)."' and Etat_echeance='AA' and Montant_echeance='$montantecheance' and Identifiant_cotisation='".$max."'"); 
							
							$num=0;
							if($req)
								{
									
									$num=mysql_num_rows($req); 
								}
								else $verif=false;
							//echo $datefin;
							 if($num==0)
								 {
								$req=mysql_query("insert into echeancier values('','".dateEN2FR($datedebut)."','".dateEN2FR($datefin)."','AA','$montantecheance','".$max."')");
								if(!$req) {$verif=false;$message.=colorer("Problème création échéance, contactez la DSI ","false");}
								}
							$datedebut=ajoutDate($datedebut,0,1,0);
							$i++;				
					}
						if($verif==true) mysql_query("commit");
						else mysql_query("rollback");
						$ok=1;
						if($_POST['modepaiement']!='P')header("location:index.php?rib=1");
						
					} 
/*********************** A  modifier avec les messages d'erreur de la cliente et décommenter **************************/
					/*elseif($date==0)$message1.=colorer(" La date de règlement ne peut être postérieure à la date d’effet","false");
					elseif($n==0)$message1.=colorer("Le montant de l’échéance réglée est faux","false");
					elseif($m==0)$message1.=colorer("Vous ne pouvez saisir un montant assuré pour ce type de produit","false");
					elseif($m1==0)$message1.=colorer("Vous devez saisir un montant assuré pour ce type de produit ","false");
					
				*/
			}
			
		
			
		
	}
}
/*elseif(isset($_POST['MM_insert']) && !$vide)
{
if(empty($_POST['datereglement']))$message=colorer("Vous devez saisir la date du règlement ","false");
elseif(empty($_POST['refreglement']))$message=colorer("Vous devez saisir la référence du règlement  ","false");
elseif(empty($_POST['montantecheanceregle']))$message=colorer("Vous devez saisir le montant de l’échéance réglée","false");

}

elseif(isset($_POST['MM_insert']) && !$bool)
{ 
if(!datevalider($_POST["datereglement"]))$message=colorer("Le format de la date du règlement est JJ-MM-SSAA, JJ étant le jour, MM le mois, SS le siècle, AA l’année","false");
elseif(!datevalide($_POST["datereglement"]))$message=colorer("La date du règlement est incorrecte","false");

elseif( !verifLibelle("refreglement"))$message=colorer("La référence du règlement saisie comporte des caractères spéciaux interdits ","false");
elseif(!verifNumeric($_POST["montantecheanceregle"]))$message=colorer("Le montant de l’échéance réglée doit être numérique ","false");
elseif(!empty($_POST['montantdroitentre']) && !verifNumeric($_POST["montantdroitentre"]))$message=colorer("Le montant  des droits d’entrée  doit être numérique ","false");
elseif(!empty($_POST['montantassure']) && !verifNumeric($_POST["montantassure"]))$message=colorer("Le montant assuré réglée doit être numérique ","false");


}*/
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Paiement</title>
<link rel="stylesheet" type="text/css" href="../../../css/main.css" />
            <link rel="stylesheet" type="text/css" href="css.css" />
			<!--[if IE 7]>
            	<link rel="stylesheet" type="text/css" href="../../../css/ie7.css" />
            	<link rel="stylesheet" type="text/css" href="form_ie7.css" />
            <![endif]-->
		</head>

<body>
<div id="sf_menu1">
<h3>Production </h3>
<?php
	

	if(isset($message) && !empty($message)){
		echo $message;
	}
	if(isset($message1) && !empty($message1)){
		echo $message1;
	}
	$nommodule="Paiement";
	//$nommodule2="Liste des adresse";
	$nom_module_saisie="Ecran saisie";
?>
</div>
<div class="cleared"></div>

<div class="corps1">
<div class="cleared"></div>
</head>

<body>
<form id="form1" name="form1" method="post" action="index.php">
 <div class="imgleft"></div>
	<div class="imgmiddle">
    <div class="btn">
    	<span class="btnleft"></span>
        <span class="btnmiddle">
        	<h5><?php echo $nommodule; ?></h5>
        </span><span class="btnright"></span>
    </div>
  	<div class="btn1">
    	<span class="btnleft"></span>
        <span class="btnmiddle">
        	<h5><?php echo $nom_module_saisie; ?></h5>
        </span>
        <span class="btnright"></span>
    </div>
	<div class="formulaire">
  <table class="tabform">
    <tr>
      <td height="24">MODE DE PAIEMENT</td>
      <td width="298"><select name="modepaiement" id="modepaiement"  >
      <?php $requete=mysql_query("select elementdico.* from dictionnaire,elementdico where dictionnaire.Code_table='M0006' and dictionnaire.Identifiant_table=elementdico.Identifiant_table");
	 
	  while($reponse=mysql_fetch_array($requete)) {?>
        <option <?php if(isset($_SESSION['modepaiement'])) echo remind_select1('modepaiement',$reponse["Code_element"]); else  echo remind_select('modepaiement',$reponse["Code_element"]);?> value="<?php echo $reponse["Code_element"];?>"><?php echo $reponse["Nom_element"];?></option>
        <?php }?>
        </select>      </td>
    </tr>
    <tr>
      <td height="24">MONTANT DE COTISATION</td>
      <td><label>
        <input   name="montantcotis" type="text" disabled="disabled" class="resizeall" id="montantcotis" value="<?php if(isset($_SESSION["montantcotisation"])) echo $_SESSION["montantcotisation"]?>" maxlength="10" />
      </label></td>
    </tr>
    <tr>
      <td height="24">DONT FRAIS ECHEANCE</td>
      <td> <input name="fraisecheance" disabled="disabled" type="text" class="resizeall" id="fraisecheance"  value="<?php if(isset($_SESSION["montantfraisecheance"])) echo $_SESSION["montantfraisecheance"]?>" maxlength="10" /></td>
    </tr>
  </table>
  
  </div></div>
    

<div class="imgright"></div>				
<div class="bt1"> <a href="refexterne/saisierefexterne.php<?php if(!empty($_SERVER['QUERY_STRING'])) echo "?".$_SERVER['QUERY_STRING']?>"><span class="btleft"></span>
        <span class="btmiddle">Référence externe</span>
        <span class="btright"></span>
    </a></div> 
   
   
   <?php if((!isset($_POST['modepaiement']) &&  !isset($_SESSION['modepaiement'])) || (isset($_POST['modepaiement']) && $_POST['modepaiement']!="P") ) 
	  echo " <div class=\"bt\"> <a href=\"#\"><span class=\"btleft\"></span>
        <span class=\"btmiddle\">RIB</span>
        <span class=\"btright\"></span>
    </a></div> "; 
	  elseif($_POST['modepaiement']=="P"  || $_SESSION['modepaiement']=="P") echo "	  
	  <div class=\"bt\"> <a href=\"rib/index.php\"><span class=\"btleft\"></span>
        <span class=\"btmiddle\">RIB</span>
        <span class=\"btright\"></span>
    </a></div>";?>
   <div class="bt"> <a href="../index.php"><span class="btleft"></span>
        <span class="btmiddle">Annuler</span>
        <span class="btright"></span>
    </a></div>  
	<div class="bt"> <a href="../index.php?retour=0<?php if(isset($ok) && $ok==1 && isset($_SESSION['modepaiement']) && $_SESSION['modepaiement']=="P")echo "?rib=1" ?>"><span class="btleft"></span>
        <span class="btmiddle">Retour</span>
        <span class="btright"></span>
    </a></div>  
    <?php  if(isset($ok) && $ok==1 || ($_GET['rib'])){?>   
	
      <div class="bt">
	<span class="btleft"></span><a href="#"></span>
	 <span class="btmiddle">Valider</span>
     <span class="btright"></span></a></div>   
     <?php 
	 } else
	 { ?><div class="bt">
	<span class="btleft"></span><input type="submit"  value="Valider"  class="resizeall btmiddle"/>
    <span class="btright"></span></div>
    <?php }
	?>       
      
	      
   <div class="cleared"></div>
  <input type="hidden" name="MM_insert" value="form1" />
</form> </div>



</body>
</html>
<?php
mysql_free_result($rs_tarif);
?>
<?php ob_end_flush();?>